<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class share_db extends Model{
	public $pk = 'share_id';
	public $table = 'ptx_share';

	var $linker = array(
			'item'=>array(
					'type' => 'hasone',
					'map' => 'item',
					'mapkey' => 'item_id',
					'ftable' => 'ptx_item',
					'fkey' => 'item_id',
					'enabled' => true
			),
			'detail'=>array(
					'type' => 'hasone',
					'map' => 'detail',
					'mapkey' => 'item_id',
					'ftable' => 'ptx_item_detail',
					'fkey' => 'item_id',
					'enabled' => false
			),
			'user'=>array(
					'type' => 'hasone',
					'map' => 'user',
					'mapkey' => 'user_id',
					'ftable' => 'ptx_user',
					'fkey' => 'user_id',
					'enabled' => true
			),
			'category'=>array(
					'type' => 'hasone',
					'map' => 'category',
					'mapkey' => 'category_id',
					'ftable' => 'ptx_category',
					'fkey' => 'category_id',
					'enabled' => true
			),
			'store'=>array(
					'type' => 'hasone',
					'map' => 'store',
					'mapkey' => 'store_id',
					'ftable' => 'ptx_store',
					'fkey' => 'store_id',
					'enabled' => false
			),
			'album'=>array(
					'type' => 'hasone',
					'map' => 'album',
					'mapkey' => 'album_id',
					'ftable' => 'ptx_album',
					'fkey' => 'album_id',
					'enabled' => true
			)
	);
	var $select_fields =
	" ptx_share.*,
			item.item_id,item.is_show,item.image_path_0,item.image_path_1,item.image_path_2,item.width,item.height,item.cloud,
			item.title,item.keyword,item.keyword_search,item.share_type,item.item_type,item.summary,item.price,item.total_images,item.color,
			category.category_name_cn,category.category_name_en,album.album_title ";

	function addone($data){
		$attrs = array('item_id','poster_id','poster_nickname','original_id','user_id','user_nickname','total_comment'
				,'total_click','total_like','total_forwarding','create_time','comments','category_id','album_id','channel','store_id');
		$insertData = array();
		foreach ($attrs as $attr){
			if($data[$attr]) $insertData[$attr]=$data[$attr];
		}
		$insertData['create_time']=TIMESTAMP;
		$insertData['lastcomment_time'] = TIMESTAMP;
		return $this->create($insertData);
	}

	function updateone($shareid,$data){
		$attrs = array('item_id','poster_id','poster_nickname','original_id','user_id','user_nickname','total_comment'
				,'total_click','total_like','total_forwarding','create_time','comments','category_id','album_id','channel','store_id');
		$insertData = array();
		foreach ($attrs as $attr){
			if($data[$attr]) $insertData[$attr]=$data[$attr];
		}
		return $this->update(array('share_id'=>$shareid),$insertData);
	}


	private function init_conditions($conditions){
		$conditions_item = ' item.is_deleted=0 ';
		$conditions_user = ' user.is_deleted=0 ';
		$conditions_share = NULL;
		$conditions_category = NULL;

		$this->linker['user']['enabled'] = true;
		$this->linker['user']['condition'] = $conditions_user;
		if(isset($conditions['keyword'])){
			$keyword = $this->escape($conditions['keyword']);
			$conditions_item .= "AND MATCH (item.keyword_search) AGAINST ({$keyword} IN BOOLEAN MODE) ";
		}
		
		if(isset($conditions['likekeyword'])){
			$likeword = $this->escape("%{$conditions['likekeyword']}%");
			$conditions_item .= "AND item.title LIKE $likeword ";
		}
		if(isset($conditions['color'])){
			$color = $this->escape($conditions['color']);
			$conditions_item .= "AND item.color='{$color}' AND item.item_type!='video'";
		}
		if(isset($conditions['type'])){
			$color = $this->escape($conditions['color']);
			switch ($conditions['type']) {
				case 'goods':
					$conditions_item .= "AND item.price>0 ";
					break;
				case 'video':
					$conditions_item .= "AND item.item_type='video' ";
					break;
				case 'share':
					$conditions_item .= "AND item.item_type='image' AND (item.price=0 OR item.price IS NULL) ";
					break;
				case 'article':
					$conditions_item .= "AND item.item_type='article' ";
					break;
				case 'noarticle':
					$conditions_item .= "AND item.item_type<>'article' ";
					break;
			}
		}
		if(isset($conditions['notop'])){
			if(isset($conditions['category_id'])||isset($conditions['category_in'])){
				$conditions_share .= 'AND ptx_share.dtype != \'2\' AND ptx_share.dtype != \'3\'';
			}else{
				$conditions_share .= 'AND ptx_share.dtype != \'2\' ';
			}
		}
		if(isset($conditions['dtype'])){
			$conditions_share .= 'AND ptx_share.dtype = \''.$conditions['dtype'].'\' ';
		}
		if(isset($conditions['dtype_in'])){
			$conditions_share .= 'AND (';
			if($cs = $conditions['dtype_in']){
				$cond = array();
				foreach ($cs as $s) {
					$cond[] = ' (ptx_share.dtype IN (\''.$s.'\')) ';
				}
				$conditions_share .= join(" OR ",$cond).') ';
			}
		}
		if(isset($conditions['category_id'])){
			$conditions_share .= 'AND ptx_share.category_id=\''.$conditions['category_id'].'\' ';
		}
		if(isset($conditions['user_id'])){
			$conditions_share .= 'AND ptx_share.user_id=\''.$conditions['user_id'].'\' ';
		}
		if(isset($conditions['find_next'])){
			$conditions_share .= 'AND ptx_share.share_id > \''.$conditions['find_next'].'\' ';
		}
		if(isset($conditions['lt_time'])){
			$conditions_share .= 'AND ptx_share.create_time < \''.$conditions['lt_time'].'\' ';
		}
		if(isset($conditions['gt_time'])){
			$conditions_share .= 'AND ptx_share.create_time >= \''.$conditions['gt_time'].'\' ';
		}
		if(isset($conditions['find_pre'])){
			$conditions_share .= 'AND ptx_share.share_id < \''.$conditions['find_pre'].'\' ';
		}
		if(isset($conditions['orgin_post'])){
			$conditions_share .= 'AND ptx_share.user_id=ptx_share.poster_id ';
		}

		if(isset($conditions['album_id'])){
			$conditions_share .= 'AND ptx_share.album_id=\''.$conditions['album_id'].'\' ';
		}

		if(isset($conditions['share_id'])){
			$conditions_share .= 'AND ptx_share.share_id=\''.$conditions['share_id'].'\' ';
		}

		if(isset($conditions['store_id'])){
			$conditions_share .= 'AND ptx_share.store_id=\''.$conditions['store_id'].'\' ';
		}

		if(isset($conditions['channel'])){
			$conditions_share .= 'AND ptx_share.channel=\''.$conditions['channel'].'\' ';
		}

		if(isset($conditions['store_id_in'])){
			$conditions_share .= 'AND (';
			if($cs = $conditions['store_id_in']['store_id']){
				$cond = array();
				foreach ($cs as $s) {
					$cond[] = ' (ptx_share.store_id IN ('.$s.')) ';
				}
				$conditions_share .= join(" OR ",$cond).') ';
			}
		}

		if(isset($conditions['channel'])||isset($conditions['store_id'])||isset($conditions['store_id_in'])){
			$this->enableLinker('store');
			$this->select_fields .= ' ,ptx_share.store_id,store.store_name ';
		}
		if(isset($conditions['id_sub'])){
			$conditions_share .= 'AND (';
			if($cs = $conditions['id_sub']['user_id']){
				$cond = array();
				foreach ($cs as $s) {
					$cond[] = ' (ptx_share.user_id IN ('.$s.')) ';
				}
				$conditions_share .= join(" OR ",$cond).') ';
			}
		}

		if(isset($conditions['category_in'])){
			$conditions_share .= 'AND (';
			$cond = array();
			foreach ($conditions['category_in'] as $s) {
				$cond[] = ' (ptx_share.category_id IN ('.$s.')) ';
			}
			$conditions_share .= join(" OR ",$cond).') ';
		}

		if(isset($conditions['is_show'])){
			$conditions_item .= 'AND item.is_show='.$conditions['is_show'].' ';
		}else{
			$conditions_item .= 'AND item.is_show>0 ';
		}

		if(isset($conditions['lowerprice'])){
			$conditions_item .= 'AND item.price>'.$conditions['lowerprice'].' ';
		}
		if(isset($conditions['higherprice'])){
			$conditions_item .= 'AND item.price<='.$conditions['higherprice'].' ';
		}
		//跟据分类英文名查找
		if(isset($conditions['category_name_en'])){
			$conditions_category .= 'AND category.category_name_en=\''.$conditions['category_name_en'].'\' ';
		}
		//查找所有商品
		if(isset($conditions['shopping'])){
			$conditions_item .= 'AND item.price>0 ';
		}
		if($conditions_item){
			$this->linker['item']['enabled'] = true;
			$this->linker['item']['condition'] = $conditions_item;
		}

		$this->linker['album']['enabled'] = true;
		$this->linker['category']['enabled'] = true;
		if($conditions_category){
			if(strpos($conditions_category, 'AND') === 0){
				$conditions_category = substr($conditions_category, 2);
			}
			$this->linker['category']['condition'] = $conditions_category;
		}
		if(strpos($conditions_share, 'AND') === 0){
			$conditions_share = substr($conditions_share, 3);
		}
		return $conditions_share;
	}

	public function search($conditions=NULL,$page,$pagesize,$fields = null,$sort=null){
		if(is_array($conditions)) $conditions = $this->init_conditions($conditions);
		$sort = isset($sort)?$sort:" ptx_share.share_id DESC ";
		$fields = isset($fields)?$fields:$this->select_fields;
		return $this->pager($page, $pagesize)->findAllJoin($conditions,$sort,$fields);
	}

	public function search_no_page($conditions=NULL,$fields = null,$sort=null,$limit=null){
		if(is_array($conditions)) $conditions = $this->init_conditions($conditions);
		$sort = isset($sort)?$sort:" ptx_share.share_id DESC ";
		$fields = isset($fields)?$fields:$this->select_fields;
		return $this->findAllJoin($conditions,$sort,$fields,$limit);
	}

	public function count($conditions,$sort=null){
		$conditions_share = $this->init_conditions($conditions);
		return $this->findCountJoin($conditions_share);
	}

	public function getShareById($sid){
		$this->enableLinker('detail');
		$this->enableLinker('item');
		$select_fields =
		" ptx_share.*,
				item.item_id,item.is_show,item.image_path_0,item.image_path_1,item.image_path_2,item.width,item.height,
				item.title,item.keyword,item.share_type,item.item_type,item.price,item.cloud,item.total_images,item.color,detail.intro,detail.reference_url,detail.reference_itemid,detail.promotion_url,
				category.category_name_cn,category.category_name_en,album.album_title ";
		$conditions['share_id'] = $sid;
		return $this->findJoin($conditions,null,$select_fields);
	}

	public function get_today_star(){
		$todaytime = strtotime(date('Ymd',TIMESTAMP));
		$sql = "SELECT DISTINCT(poster_id) AS uid, poster_nickname AS nickname, COUNT(share_id) AS posts FROM {$this->tbl_name}".
				" WHERE create_time>='$todaytime' GROUP BY uid ORDER BY posts DESC LIMIT 0,10";
		return $this->findSql($sql);
	}

	public function find_one($conditions=NULL,$sort=NULL,$fields=NULL){
		if(is_array($conditions)) $conditions = $this->init_conditions($conditions);
		$sort = isset($sort)?$sort:" ptx_share.share_id DESC ";
		$fields = isset($fields)?$fields:$this->select_fields;
		return $this->findJoin($conditions,$sort,$fields);
	}

	//获取一组数据
	public function get_all($conditions = null, $page = 1,$sort = null, $fields = null, $limit = null){
		$results = $this->spLinker()->spPager($page, 20)->findAll($conditions,$sort, $fields, $limit);
		return $results;
	}

	//获取一行数据
	public function get_one($conditions = null, $sort = null, $fields = null, $limit = null){
		$results = $this->spLinker()->find($conditions,$sort, $fields, $limit);
		return $results;
	}

	public function creat_forward($sid,$cid,$aid,$uid,$nickname){
		$share = $this->getShareById($sid);
		if($share){
			if($share['user_id']==$uid||$share['poster_id']==$uid){
				return false;
			}
			$data['item_id'] = $share['item_id'];
			$data['poster_id'] = $share['poster_id'];
			$data['poster_nickname'] = $share['poster_nickname'];
			$data['original_id'] = $share['share_id'];
			$data['user_id'] = $uid;
			$data['user_nickname'] = $nickname;
			$data['album_id'] = $aid;
			$data['category_id'] = $cid;
			$data['total_comment'] = 0;
			$data['total_click'] = 0;
			$data['total_like'] = 0;
			$data['total_forwarding'] = 0;
			$data['create_time'] = TIMESTAMP;
			$data['lastcomment_time'] = TIMESTAMP;
			$this->create($data);

			load_db('user')->add_share($uid);
			load_api('album')->update_album_cover($aid);

			$this->add_forwarding($sid);
			//$ptx_message->add_forwarding($sid,$share['title'],$uid,$share['user_id']);
			return true;
		}
		return false;
	}


	public function get_round($category_id,$limit = null){
		$dbpre = $this->dbpre;
		if($category_id)
			$where = " ptx_share.category_id = {$category_id} AND item.is_deleted=0 ORDER BY ptx_share.share_id ";
		else
			$where = " item.is_deleted=0 ORDER BY ptx_share.share_id ";
		$sql = " SELECT {$this->select_fields}
		FROM  `{$dbpre}ptx_share` AS ptx_share
		JOIN (
		SELECT ROUND(
		RAND() *
		((SELECT MAX( share_id ) FROM  `{$dbpre}ptx_share` ) - ( SELECT MIN( share_id ) FROM  `{$dbpre}ptx_share` ))
		+ ( SELECT MIN( share_id ) FROM  `{$dbpre}ptx_share` )
		) AS share_rand_id
		) AS t2
		ON ptx_share.share_id >= t2.share_rand_id
		LEFT JOIN  `{$dbpre}ptx_item` item ON ptx_share.item_id = item.item_id
		LEFT JOIN  `{$dbpre}ptx_item_detail` detail ON ptx_share.item_id = detail.item_id
		LEFT JOIN  `{$dbpre}ptx_category` category ON ptx_share.category_id = category.category_id
		LEFT JOIN  `{$dbpre}ptx_album` album ON ptx_share.album_id = album.album_id
		WHERE {$where}";

		($limit) ? $sql.= " LIMIT {$limit}" : '';

		$result = $this->findSql($sql);
		return $result;

	}

	function find_albums_by_item($item_id){
		$item_id = $this->escape($item_id);
		$sql = "SELECT DISTINCT album_id FROM {$this->tbl_name} WHERE item_id={$item_id}";
		$result = $this->findSql($sql);
		return $result;
	}

	/* function deleteByPk($pk){
		parent::deleteByPk($pk);
	//second delete comment
	$pk = $this->escape($pk);
	$update_comment_sql = " DELETE FROM `{$this->dbpre}ptx_comment` WHERE share_id=$pk ";
	$this->runSql($update_comment_sql);
	} */

	function change_channel($conditions,$channelid){
		return $this->update($conditions, array('channel_id'=>$channelid));
	}

	function add_like($share_id){
		return $this->incrField(array('share_id'=>$share_id), 'total_like');
	}

	function remove_like($share_id){
		return $this->decrField(array('share_id'=>$share_id), 'total_like');
	}

	function add_forwarding($share_id){
		return $this->incrField(array('share_id'=>$share_id), 'total_forwarding');
	}

	function add_good($share_id){
		return $this->incrField(array('share_id'=>$share_id), 'total_good');
	}

	public function addviewnum($share_id){
		return $this->incrField(array('share_id'=>$share_id), 'total_click');
	}

	function add_bad($share_id){
		return $this->incrField(array('share_id'=>$share_id), 'total_bad');
	}

	function view_count(){
		$count = $this->findSql("SELECT SUM(total_click) AS cou FROM {$this->tbl_name}");
		return $count[0]['cou']?$count[0]['cou']:0;
	}
	function like_count(){
		$count = $this->findSql("SELECT SUM(total_like) AS cou FROM {$this->tbl_name}");
		return $count[0]['cou']?$count[0]['cou']:0;
	}
	function share_count(){
		$count = $this->findSql("SELECT COUNT(*) AS cou FROM {$this->tbl_name}");
		return $count[0]['cou']?$count[0]['cou']:0;
	}
	function forwarding_count(){
		$count = $this->findSql("SELECT SUM(total_forwarding) AS cou FROM {$this->tbl_name}");
		return $count[0]['cou']?$count[0]['cou']:0;
	}
}
